<template>
  <div class="login">
    <img  :src="logo" class="sidebar-logo" />
    <img :src="BigLogoImg" alt="" :class="[BigLogoImgStyleClass]">
    <!-- <h2 style="    font-size: 60px;
    font-family: PingFang SC;
    font-weight: bold;
    color: rgba(255,255,255,1);
   margin-top: -30px;
    letter-spacing: 8px;">协同工单平台</h2> -->
    <el-form ref="loginForm" :model="loginForm" :rules="loginRules" class="login-form">
      <h3 class="title">{{title}}</h3>
      <el-form-item prop="username">
        <el-input
          v-model="loginForm.username"
          type="text"
          auto-complete="off"
          placeholder="账号"
        >
          <svg-icon slot="prefix" icon-class="user" class="el-input__icon input-icon" />
        </el-input>
      </el-form-item>
      <el-form-item prop="password">
        <el-input
          v-model="loginForm.password"
          type="password"
          auto-complete="off"
          placeholder="密码"
          @keyup.enter.native="handleLogin"
        >
          <svg-icon slot="prefix" icon-class="password" class="el-input__icon input-icon" />
        </el-input>
      </el-form-item>
      <el-form-item prop="code" v-if="captchaEnabled">
        <el-input
          v-model="loginForm.code"
          auto-complete="off"
          placeholder="验证码"
          style="width: 63%"
          @keyup.enter.native="handleLogin"
        >
          <svg-icon slot="prefix" icon-class="validCode" class="el-input__icon input-icon" />
        </el-input>
        <div class="login-code">
          <img :src="codeUrl" @click="getCode" class="login-code-img"/>
        </div>
      </el-form-item>
      <el-checkbox v-model="loginForm.rememberMe" style="margin:0px 0px 25px 0px;">记住密码</el-checkbox>
      <el-form-item style="width:100%;">
        <div>
          <el-button
            :loading="loading"
            size="medium"
            type="primary"
            style="width:45%;"
            @click.native.prevent="handleLogin"
          >
            <span v-if="!loading">登 录</span>
            <span v-else>登 录 中...</span>
          </el-button>
          <el-button
            :loading="false"
            size="medium"
            type="primary"
            style="width:45%; float: right;"
            @click.native.prevent="handleIamLogin"
          >
            <span>IAM 登 录</span>
          </el-button>
        </div>
        <div style="float: right;" v-if="register">
          <router-link class="link-type" :to="'/register'">立即注册</router-link>
        </div>
      </el-form-item>
    </el-form>
    <!--  底部  -->
    <!-- <div class="el-login-footer">
      <span>Copyright © 2019-2023 Sinosoft Co.,Ltd All Rights Reserved.</span>
    </div> -->
  </div>
</template>

<script>
import logoImg from '@/assets/logo/fsg_logo1.png'
import BigLogoImg from '@/assets/images/蓝色背景.png'

import { getCodeImg } from "@/api/login";
import Cookies from "js-cookie";
import { encrypt, decrypt } from '@/utils/jsencrypt'

export default {
  name: "Login",
  data() {
    return {
      title: '服务协同工单管理平台',
      codeUrl: "",
      logo: logoImg,
      BigLogoImg:BigLogoImg,
      loginForm: {
        username: "",
        password: "",
        rememberMe: false,
        code: "",
        uuid: "",
        iamCode: ""
      },
      loginRules: {
        username: [
          { required: true, trigger: "blur", message: "请输入您的账号" }
        ],
        password: [
          { required: true, trigger: "blur", message: "请输入您的密码" }
        ],
        code: [{ required: true, trigger: "change", message: "请输入验证码" }]
      },
      loading: false,
      // 验证码开关
      captchaEnabled: true,
      // 注册开关
      register: false,
      redirect: undefined,
      BigLogoImgStyleClass: 'BigLogoImg',
      // IAM login url
      iamLoginUrl: process.env.VUE_APP_IAM_LOGIN_URL,
    };
  },
  watch: {
    $route: {
      handler: function(route) {
        this.redirect = route.query && route.query.redirect;
      },
      immediate: true
    }
  },
  created() {
    this.getCode();
    this.getCookie();
  },
  mounted() {
    this.handleWindowResize()
    window.addEventListener('resize', this.handleWindowResize)

    // IAM code登陆认证处理
    this.handleIamAuthLogin()
  },
  methods: {
    getCode() {
      getCodeImg().then(res => {
        this.captchaEnabled = res.data.captchaEnabled === undefined ? true : res.data.captchaEnabled;
        if (this.captchaEnabled) {
          this.codeUrl = "data:image/gif;base64," + res.data.img;
          this.loginForm.uuid = res.data.uuid;
        }
      });
    },
    getCookie() {
      const username = Cookies.get("username");
      const password = Cookies.get("password");
      const rememberMe = Cookies.get('rememberMe')
      this.loginForm = {
        username: username === undefined ? this.loginForm.username : username,
        password: password === undefined ? this.loginForm.password : decrypt(password),
        rememberMe: rememberMe === undefined ? false : Boolean(rememberMe)
      };
    },
    handleLogin() {
      this.$refs.loginForm.validate(valid => {
        if (valid) {
          this.loading = true;
          if (this.loginForm.rememberMe) {
            Cookies.set("username", this.loginForm.username, { expires: 30 });
            Cookies.set("password", encrypt(this.loginForm.password), { expires: 30 });
            Cookies.set('rememberMe', this.loginForm.rememberMe, { expires: 30 });
          } else {
            Cookies.remove("username");
            Cookies.remove("password");
            Cookies.remove('rememberMe');
          }
          this.$store.dispatch("Login", this.loginForm).then(() => {
            // this.$router.push({ path: '/work/todo'}).catch(()=>{});
            // this.$router.push({ path: this.redirect || "/" }).catch(()=>{});
            location.replace(`${location.origin}/`)
          }).catch(() => {
            this.loading = false;
            if (this.captchaEnabled) {
              this.getCode();
            }
          });
        }
      });
    },
    handleWindowResize() {
      // 1366 / 640
      if (window.innerHeight < 690 && window.innerHeight >= 590) {
        console.log('MINI')
        this.BigLogoImgStyleClass = 'BigLogoImg-MINI'
      } 
      // 1280 / 551
      else if (window.innerHeight < 590 && window.innerHeight > 500) {
        console.log('MINIX')
        this.BigLogoImgStyleClass = 'BigLogoImg-MINIX'
      } else {
        console.log('BigLogoImg')
        this.BigLogoImgStyleClass = 'BigLogoImg'
      }
    },
    handleIamLogin() {
      window.location.replace(this.iamLoginUrl)
    },
    handleIamAuthLogin() {
      let iamCode = this.$route.query && this.$route.query.code;
      let toParam = ''
      if (iamCode) {
        this.loginForm.iamCode = iamCode
      } else if (URLSearchParams) {
        const urlParams = new URLSearchParams(window.location.search)
        if (urlParams) {
          this.loginForm.iamCode = urlParams.get('code')
          toParam = urlParams.get('to')
        }
      }
      if (!this.loginForm.iamCode) {
        return
      } else {
        const cachedIamCode = localStorage.getItem('IAM_CODE_CACHE')
        if (cachedIamCode && cachedIamCode === this.loginForm.iamCode) {
          console.warn("IAM_CODE_CACHE has used !!! ", cachedIamCode)
          return
        }
      }
      this.$modal.loading("IAM登陆认证中，请稍候...");
      this.$store.dispatch("IamLogin", this.loginForm).then(() => {
        setTimeout(() => {
          this.$modal.closeLoading();
          if (toParam && toParam.split('__')) {
            switch (toParam.split('__')[0]) {
              case 'todo':
                let busKey = toParam.split('__')[1]
                if (busKey) {
                  busKey = '?businessKey=' + busKey
                } else {
                  busKey = ''
                }
                location.replace(`${location.origin}/#/work/todo${busKey}`)
                break;
              case 'own':
                let ownBusKey = toParam.split('__')[1]
                if (ownBusKey) {
                  ownBusKey = '?businessKey=' + ownBusKey
                } else {
                  ownBusKey = ''
                }
                location.replace(`${location.origin}/#/work/own${ownBusKey}`)
                break;
            
              default:
                location.replace(`${location.origin}/`)
                break;
            }
          } else {
            // this.$router.push({ path: this.redirect || "/" }).catch(() => { });
            location.replace(`${location.origin}/`)
          }
          localStorage.setItem('IAM_CODE_CACHE', this.loginForm.iamCode)
        }, 800);
      }).catch(() => {
        this.$modal.closeLoading();
        // this.$modal.msgError("认证失败！");
      });
    }
  }
};
</script>

<style rel="stylesheet/scss" lang="scss">
.login {
  display: flex;
  justify-content: space-around;
  align-items: center;
  height: 100%;
  background-image: url("../assets/images/白色背景.png");
  background-size: cover;
}
.title {
  margin: 0px auto 30px auto;
  text-align: center;
  color: #161515;
  font-weight: 800;
  font-size: 28px;
}

.login-form {
  position:absolute;
  z-index: 3;
  border-radius: 6px;
  background: #ffffff;
  width: 400px;
  padding: 25px 25px 5px 25px;
  top: 30%;
  left: 52%;
  .el-input {
    height: 38px;
    input {
      height: 38px;
    }
  }
  .input-icon {
    height: 39px;
    width: 14px;
    margin-left: 2px;
  }
}
.login-tip {
  font-size: 13px;
  text-align: center;
  color: #bfbfbf;
}
.login-code {
  width: 33%;
  height: 38px;
  float: right;
  img {
    cursor: pointer;
    vertical-align: middle;
  }
}
.el-login-footer {
  height: 40px;
  line-height: 40px;
  position: fixed;
  bottom: 0;
  width: 100%;
  text-align: center;
  color: #008bf1;
  font-family: Arial;
  font-size: 12px;
  letter-spacing: 1px;
}
.login-code-img {
  height: 38px;
}
.login .sidebar-logo{
  position: absolute;
  top: 60px;
  left: 43px;
  width: 376px;
  height: 40px;
  z-index: 1;
}
.BigLogoImg{
  z-index: 0;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%,-50%);
}
.BigLogoImg-MINI{
  z-index: 0;
  position: absolute;
  top: 20%;
  left: 20%;
  width: 857px;
  height: 500px;
}
.BigLogoImg-MINIX{
  z-index: 0;
  position: absolute;
  top: 20%;
  left: 25%;
  width: 757px;
  height: 441px;
}
</style>
